import { Model, DataTypes, Optional } from 'sequelize';
import { sequelize } from '../config/database';
import User from './User';

export interface SocialRelationAttributes {
    id: string;
    userId: string;
    targetId: string;
    type: 'follow' | 'friend';
    status: 'pending' | 'accepted' | 'rejected';
    createdAt?: Date;
    updatedAt?: Date;
}

export interface SocialRelationCreationAttributes extends Optional<SocialRelationAttributes, 'id' | 'createdAt' | 'updatedAt'> { }

class SocialRelation extends Model<SocialRelationAttributes, SocialRelationCreationAttributes> implements SocialRelationAttributes {
    public id!: string;
    public userId!: string;
    public targetId!: string;
    public type!: 'follow' | 'friend';
    public status!: 'pending' | 'accepted' | 'rejected';
    public readonly createdAt!: Date;
    public readonly updatedAt!: Date;

    public static associate(models: any) {
        SocialRelation.belongsTo(models.User, {
            foreignKey: 'userId',
            as: 'user'
        });
        SocialRelation.belongsTo(models.User, {
            foreignKey: 'targetId',
            as: 'target'
        });
    }
}

export const initSocialRelation = (sequelize: any) => {
    SocialRelation.init(
        {
            id: {
                type: DataTypes.UUID,
                defaultValue: DataTypes.UUIDV4,
                primaryKey: true
            },
            userId: {
                type: DataTypes.UUID,
                allowNull: false,
                references: {
                    model: 'users',
                    key: 'id'
                }
            },
            targetId: {
                type: DataTypes.UUID,
                allowNull: false,
                references: {
                    model: 'users',
                    key: 'id'
                }
            },
            type: {
                type: DataTypes.ENUM('follow', 'friend'),
                allowNull: false
            },
            status: {
                type: DataTypes.ENUM('pending', 'accepted', 'rejected'),
                defaultValue: 'pending'
            }
        },
        {
            sequelize,
            modelName: 'SocialRelation',
            tableName: 'social_relations',
            timestamps: true,
            indexes: [
                {
                    unique: true,
                    fields: ['userId', 'targetId', 'type']
                }
            ]
        }
    );
};

export default SocialRelation; 